package com.qixin.modules.eaLoan.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.*;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.qixin.modules.ea.entity.EaTravel;
import com.qixin.modules.eaApplication.entity.EaBusinessApply;
import com.qixin.modules.eaBasic.entity.EaTask;
import com.qixin.modules.eaLoan.entity.EaLoanbill;
import com.qixin.modules.eaLoan.mapper.EaLoanbillMapper;
import com.qixin.modules.eaLoan.mapper.EaRepaymentbillMapper;
import com.qixin.modules.eaLoan.service.IEaLoanbillService;
import com.qixin.modules.eaLoan.vo.EaRepaymentPrintVo;
import com.qixin.utils.PreciseCompute;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.util.ConvertUpMoneyUtil;
import org.jeecg.common.util.FillRuleUtil;
import org.jeecg.modules.activiti.entity.ActZTask;
import org.jeecg.modules.activiti.mapper.ActZTaskMapper;
import org.jeecg.modules.activity.service.ActivityCommonService;
import org.jeecg.modules.nc.entity.NcPersonnel;
import org.jeecg.modules.nc.service.INcInoutbusiclassService;
import org.jeecg.modules.nc.service.INcPersonnelService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import com.qixin.modules.eaLoan.entity.EaLoanbillDetail;
import com.qixin.modules.eaLoan.entity.EaRepaymentbill;
import com.qixin.modules.eaLoan.vo.EaRepaymentbillPage;
import com.qixin.modules.eaLoan.service.IEaRepaymentbillService;
import com.qixin.modules.eaLoan.service.IEaLoanbillDetailService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: ea_repaymentbill
 * @Author: qixin-boot
 * @Date: 2022-01-21
 * @Version: V1.0
 */
@Api(tags = "还款单")
@RestController
@RequestMapping("/eaLoan/eaRepaymentbill")
@Slf4j
public class EaRepaymentbillController {
    @Autowired
    private IEaRepaymentbillService eaRepaymentbillService;
    @Autowired
    private IEaLoanbillDetailService eaLoanbillDetailService;
    @Autowired
    private INcPersonnelService ncPersonnelService;
    @Autowired
    private EaLoanbillMapper eaLoanbillMapper;
    @Autowired
    private EaRepaymentbillMapper eaRepaymentbillMapper;
    @Autowired
    private ActZTaskMapper actZTaskMapper;
    @Autowired
    private INcInoutbusiclassService ncInoutbusiclassService;
    // 工作流公共执行类
    @Autowired
    private ActivityCommonService activityCommonService;

    /**
     * 分页列表查询
     *
     * @param eaRepaymentbill
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @ApiOperation(value = "还款单-分页列表查询", notes = "还款单-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(EaRepaymentbill eaRepaymentbill,
                                   @RequestParam(name = "billDateBegin", required = false) String billDateBegin,
                                   @RequestParam(name = "billDateEnd", required = false) String billDateEnd,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   @RequestParam(name = "billCode", required = false) String billCode,
                                   HttpServletRequest req) {
        QueryWrapper<EaRepaymentbill> queryWrapper = QueryGenerator.initQueryWrapper(eaRepaymentbill, req.getParameterMap());
        //add-begin-by wujinbiao for 添加查询条件 列表排序，创建人
        if (StringUtils.isNotBlank(billDateBegin)) {
            queryWrapper.ge("bill_date", billDateBegin);
        }
        if (StringUtils.isNotBlank(billDateEnd)) {
            queryWrapper.le("bill_date", billDateEnd);
        }
        if (StringUtils.isNotBlank(billCode)) {
            // 单据编号模糊查询
            queryWrapper.like("bill_no", billCode);
        }
        queryWrapper.orderByDesc("create_time");
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        queryWrapper.eq("create_by", loginUser.getId());
        //add-end-by wujinbiao for 添加查询条件
        Page<EaRepaymentbill> page = new Page<EaRepaymentbill>(pageNo, pageSize);
        IPage<EaRepaymentbill> pageList = eaRepaymentbillService.page(page, queryWrapper);
        List<EaRepaymentbill> records = pageList.getRecords();
        for (EaRepaymentbill eaRepaymentbill1 : records) {
            NcPersonnel ncPersonnel = ncPersonnelService.queryById(eaRepaymentbill1.getPersonId());
            if (ncPersonnel != null) {
                eaRepaymentbill1.setPersonIdName(ncPersonnel.getName());
            }
        }
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param eaRepaymentbillPage
     * @return
     */
    @AutoLog(value = "还款单-添加")
    @ApiOperation(value = "还款单-添加", notes = "还款单-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody EaRepaymentbillPage eaRepaymentbillPage) {
        EaRepaymentbill eaRepaymentbill = new EaRepaymentbill();
        BeanUtils.copyProperties(eaRepaymentbillPage, eaRepaymentbill);
        // update-begin-Autor: wjb date: 2022-02-09 10:47 for: 生成单据编号
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("prefix", "HK"); // 编码前缀
        Object result = FillRuleUtil.executeRule("common_code", jsonObj);
        eaRepaymentbill.setBillNo(result.toString());
        // update-end-Autor: wjb date: 2022-02-09 10:47 for: 生成单据编号
        eaRepaymentbill.setState(0);
        eaRepaymentbillService.saveMain(eaRepaymentbill, eaRepaymentbillPage.getEaLoanbillDetailList());
        //add-begin-by wjb 2022-02-07 for 返回主表、子表数据给前端
        EaRepaymentbillPage resultPage = new EaRepaymentbillPage();
        BeanUtils.copyProperties(eaRepaymentbill, resultPage);

        // update-begin-author wjb 2022-02-11 09:16 返回关联的申请单实体
        // resultPage.setEaLoanbillDetailList(eaRepaymentbillPage.getEaLoanbillDetailList());
        Map<String, Object> paramsMap = new HashMap<String, Object>();
        paramsMap.put("ea_repaymentbill_id", eaRepaymentbill.getId());
        List<EaLoanbill> eaLoanbills = eaLoanbillMapper.selectByMap(paramsMap);
        // 将冲销金额、当前需还金额、余额返回给前端
        for (EaLoanbill eaLoanbill : eaLoanbills) {
            eaLoanbill.setReveralAmount(eaLoanbill.getLoanAmount());
            eaLoanbill.setCurrentRemainAmount(new BigDecimal(0));
            eaLoanbill.setRemainAmount(new BigDecimal(0));
        }
        List<EaLoanbill> eaLoanbillList = new ArrayList<>();
        eaLoanbillList.addAll(eaLoanbills);
        resultPage.setEaLoanbillDetailList(eaLoanbillList);
        // update-end-author wjb 2022-02-11 09:16 返回关联的申请单实体

        //add-end-by wjb 2022-02-07 for 返回主表、子表数据给前端
        return Result.OK(resultPage);
    }

    /**
     * 编辑
     *
     * @param eaRepaymentbillPage
     * @return
     */
    @AutoLog(value = "还款单-编辑")
    @ApiOperation(value = "还款单-编辑", notes = "还款单-编辑")
    @PostMapping(value = "/edit")
    public Result<?> edit(@RequestBody EaRepaymentbillPage eaRepaymentbillPage) {
        EaRepaymentbill eaRepaymentbill = new EaRepaymentbill();
        BeanUtils.copyProperties(eaRepaymentbillPage, eaRepaymentbill);
        EaRepaymentbill eaRepaymentbillEntity = eaRepaymentbillService.getById(eaRepaymentbill.getId());
        if (eaRepaymentbillEntity == null) {
            return Result.error("未找到对应数据");
        }
        eaRepaymentbillService.updateMain(eaRepaymentbill, eaRepaymentbillPage.getEaLoanbillDetailList());
        // update-begin-author wjb 2022-02-11 09:16 返回关联的申请单实体
        EaRepaymentbillPage resultPage = new EaRepaymentbillPage();
        BeanUtils.copyProperties(eaRepaymentbill, resultPage);
        // resultPage.setEaLoanbillDetailList(eaRepaymentbillPage.getEaLoanbillDetailList());
        Map<String, Object> paramsMap = new HashMap<String, Object>();
        paramsMap.put("ea_repaymentbill_id", eaRepaymentbill.getId());
        List<EaLoanbill> eaLoanbills = eaLoanbillMapper.selectByMap(paramsMap);
        // 将冲销金额、当前需还金额、余额返回给前端
        for (EaLoanbill eaLoanbill : eaLoanbills) {
            eaLoanbill.setReveralAmount(eaLoanbill.getLoanAmount());
            eaLoanbill.setCurrentRemainAmount(new BigDecimal(0));
            eaLoanbill.setRemainAmount(new BigDecimal(0));
        }
        List<EaLoanbill> eaLoanbillList = new ArrayList<>();
        eaLoanbillList.addAll(eaLoanbills);
        resultPage.setEaLoanbillDetailList(eaLoanbillList);
        // update-end-author wjb 2022-02-11 09:16 返回关联的申请单实体

        return Result.OK(resultPage);
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "还款单-通过id删除")
    @ApiOperation(value = "还款单-通过id删除", notes = "还款单-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        QueryWrapper<EaRepaymentbill> params = new QueryWrapper<>();
        params.eq("id", id);
        EaRepaymentbill eaRepaymentbill = eaRepaymentbillService.getOne(params);
        if (eaRepaymentbill != null && eaRepaymentbill.getState() > 0) {
            return Result.error("该单据已发起流程,不可删除!");
        }
        eaRepaymentbillService.delMain(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "还款单-批量删除")
    @ApiOperation(value = "还款单-批量删除", notes = "还款单-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.eaRepaymentbillService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "还款单-通过id查询", notes = "还款单-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        EaRepaymentbill eaRepaymentbill = eaRepaymentbillService.getById(id);
        if (eaRepaymentbill == null) {
            return Result.error("未找到对应数据");
        }
        // 返回还款人中文
        if (StringUtils.isNotBlank(eaRepaymentbill.getPersonId())) {
            NcPersonnel ncPersonnel = ncPersonnelService.queryById(eaRepaymentbill.getPersonId());
            if (ncPersonnel != null) {
                eaRepaymentbill.setPersonIdName(ncPersonnel.getName());
            }
        }
        // update-begin-author wjb 2022-02-11 09:16 返回关联的申请单实体

//		//查询子表数据
//		List<EaLoanbillDetail> eaLoanbillDetails = eaLoanbillDetailService.selectByMainId(eaRepaymentbill.getId());
//		eaRepaymentbillPage.setEaLoanbillDetailList(eaLoanbillDetails);

        EaRepaymentbillPage resultPage = new EaRepaymentbillPage();
        BeanUtils.copyProperties(eaRepaymentbill, resultPage);
        // resultPage.setEaLoanbillDetailList(eaRepaymentbillPage.getEaLoanbillDetailList());
        Map<String, Object> paramsMap = new HashMap<String, Object>();
        paramsMap.put("ea_repaymentbill_id", eaRepaymentbill.getId());
        List<EaLoanbill> eaLoanbills = eaLoanbillMapper.selectByMap(paramsMap);
        // 将冲销金额、当前需还金额、余额返回给前端
        for (EaLoanbill eaLoanbill : eaLoanbills) {
            eaLoanbill.setReveralAmount(eaLoanbill.getLoanAmount());
            eaLoanbill.setCurrentRemainAmount(new BigDecimal(0));
            eaLoanbill.setRemainAmount(new BigDecimal(0));
        }
        List<EaLoanbill> eaLoanbillList = new ArrayList<>();
        eaLoanbillList.addAll(eaLoanbills);
        resultPage.setEaLoanbillDetailList(eaLoanbillList);
        // update-end-author wjb 2022-02-11 09:16 返回关联的申请单实体

        return Result.OK(resultPage);
    }


    /**
    * @Description 还款单打印模板数据
    * @author  wujinbiao
    * @date 2022/3/14
    * @param id
    * @return org.jeecg.common.api.vo.Result<?>
    */
    @ApiOperation(value = "还款单打印模板数据", notes = "还款单打印模板数据")
    @GetMapping(value = "/selectById")
    public Result<?> selectById(@RequestParam(name = "id", required = true) String id) {
        EaRepaymentPrintVo eaRepaymentPrintVo = new EaRepaymentPrintVo();
        EaRepaymentbill eaRepaymentbill = eaRepaymentbillService.getById(id);
        if (eaRepaymentbill == null) {
            return Result.error("未找到对应数据");
        } else {
            BeanUtils.copyProperties(eaRepaymentbill, eaRepaymentPrintVo);
            // 还款人中文返回
            if (StringUtils.isNotBlank(eaRepaymentbill.getPersonId())) {
                NcPersonnel ncPersonnel = ncPersonnelService.queryById(eaRepaymentbill.getPersonId());
                if (ncPersonnel != null) {
                    eaRepaymentPrintVo.setPersonIdName(ncPersonnel.getName());
                }
            }
            // 费用项目中文返回
            if (StringUtils.isNotBlank(eaRepaymentbill.getIndexId())) {
                String indexIdName = ncInoutbusiclassService.getIndexIdName(eaRepaymentbill.getIndexId());
                eaRepaymentPrintVo.setIndexIdName(indexIdName);
            }
            // 还款金额转为大写金额
            BigDecimal repaymentAmount = eaRepaymentbill.getRepaymentAmount() != null ? eaRepaymentbill.getRepaymentAmount() : new BigDecimal(0);
            String repaymentAmountStr = ConvertUpMoneyUtil.toChinese(String.valueOf(repaymentAmount));
            eaRepaymentPrintVo.setRepaymentAmount_cn(repaymentAmountStr);
            // 审批记录
            if (StringUtils.isNotBlank(eaRepaymentbill.getProcInstId())){
                List<Map<String, Object>> nodeList = activityCommonService.getNodeList(eaRepaymentbill.getProcInstId());
                eaRepaymentPrintVo.setSpjl(nodeList);
            }
        }
        return Result.OK(eaRepaymentPrintVo);
    }


    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "借款单明细-主表ID查询", notes = "借款单明细-通主表ID查询")
    @GetMapping(value = "/queryEaLoanbillDetailByMainId")
    public Result<?> queryEaLoanbillDetailListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<EaLoanbillDetail> eaLoanbillDetailList = eaLoanbillDetailService.selectByMainId(id);
        return Result.OK(eaLoanbillDetailList);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param eaRepaymentbill
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, EaRepaymentbill eaRepaymentbill) {
        // Step.1 组装查询条件查询数据
        QueryWrapper<EaRepaymentbill> queryWrapper = QueryGenerator.initQueryWrapper(eaRepaymentbill, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        //Step.2 获取导出数据
        List<EaRepaymentbill> queryList = eaRepaymentbillService.list(queryWrapper);
        // 过滤选中数据
        String selections = request.getParameter("selections");
        List<EaRepaymentbill> eaRepaymentbillList = new ArrayList<EaRepaymentbill>();
        if (oConvertUtils.isEmpty(selections)) {
            eaRepaymentbillList = queryList;
        } else {
            List<String> selectionList = Arrays.asList(selections.split(","));
            eaRepaymentbillList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
        }

        // Step.3 组装pageList
        List<EaRepaymentbillPage> pageList = new ArrayList<EaRepaymentbillPage>();
        for (EaRepaymentbill main : eaRepaymentbillList) {
            EaRepaymentbillPage vo = new EaRepaymentbillPage();
            BeanUtils.copyProperties(main, vo);
            List<EaLoanbillDetail> eaLoanbillDetailList = eaLoanbillDetailService.selectByMainId(main.getId());
//          vo.setEaLoanbillDetailList(eaLoanbillDetailList);
            pageList.add(vo);
        }

        // Step.4 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "ea_repaymentbill列表");
        mv.addObject(NormalExcelConstants.CLASS, EaRepaymentbillPage.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("ea_repaymentbill数据", "导出人:" + sysUser.getRealname(), "ea_repaymentbill"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<EaRepaymentbillPage> list = ExcelImportUtil.importExcel(file.getInputStream(), EaRepaymentbillPage.class, params);
                for (EaRepaymentbillPage page : list) {
                    EaRepaymentbill po = new EaRepaymentbill();
                    BeanUtils.copyProperties(page, po);
                    eaRepaymentbillService.saveMain(po, page.getEaLoanbillDetailList());
                }
                return Result.OK("文件导入成功！数据行数:" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.OK("文件导入失败！");
    }

    /**
     * description:
     * create time: 2021/12/24 9:52
     * create by: wjb
     *
     * @return
     * @params billId
     */
    @AutoLog(value = "还款单状态更新")
    @ApiOperation(value = "还款单状态更新", notes = "还款单状态更新")
    @PutMapping(value = "/updateLoanBillState")
    public Result<?> updateLoanBillState(@RequestParam(name = "billIds", required = true) String billIds) {
        if (StringUtils.isNotBlank(billIds)) {
            String[] ids = billIds.split(",");
            // 还款单id
            String eaRepaymentbillId = "";
            // 借款金额
            double loanAmount = 0;
            if (ids.length > 0) {
                for (String id : ids) {
                    // 获取借款单信息
                    EaLoanbill eaLoanbill = eaLoanbillMapper.selectById(id);
                    eaRepaymentbillId = eaLoanbill.getEaRepaymentbillId();
                    if (eaLoanbill != null && eaLoanbill.getEaRepaymentbillId() != null) {
                        // 取消借款单的使用标识
                        eaLoanbillMapper.updateByBillId(id);
                        // 获取借款金额
                        loanAmount = PreciseCompute.add(loanAmount, eaLoanbill.getLoanAmount().doubleValue());
                    }
                }
            }

            if (ids.length > 0) {
                if (StringUtils.isNotBlank(eaRepaymentbillId)) {
                    // 还款单表单数据修改
                    EaRepaymentbill eaRepaymentbill = eaRepaymentbillMapper.selectById(eaRepaymentbillId);
                    eaRepaymentbill.setRepaymentAmount(new BigDecimal(PreciseCompute.sub(eaRepaymentbill.getRepaymentAmount().doubleValue(), loanAmount)));
                    eaRepaymentbillService.updateById(eaRepaymentbill);
                }
            }

            // 代办任务修改
            // 修改待办列表的还款金额
            EaRepaymentbill eaRepaymentbill = eaRepaymentbillMapper.selectById(eaRepaymentbillId);
            Map<String, Object> params = new HashMap<>();
            params.put("table_id", eaRepaymentbillId);
            List<ActZTask> actZTasks = actZTaskMapper.selectByMap(params);
            if (actZTasks.size() > 0) {
                // 修改任务列表 对应的借款金额
                ActZTask actZTask = actZTasks.get(0);
                actZTask.setTotalFee(eaRepaymentbill.getRepaymentAmount());
                actZTaskMapper.updateById(actZTask);
            }

        }
        return Result.OK();
    }

}
